package com.dingyx.ps.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dingyx.ps.mapper.GoodsListMapper;
import com.dingyx.ps.mapper.ManagerUserMapper;
import com.dingyx.ps.mapper.MemberListMapper;
import com.dingyx.ps.mapper.ReceiveRecordMapper;
import com.dingyx.ps.model.PageEntity;
import com.dingyx.ps.model.ReturnT;
import com.dingyx.ps.model.entity.GoodsListDTO;
import com.dingyx.ps.model.entity.ManagerUserDTO;
import com.dingyx.ps.model.entity.MemberListDTO;
import com.dingyx.ps.model.entity.ReceiveRecordDTO;
import com.dingyx.ps.model.export.MemberExport;
import com.dingyx.ps.model.export.ReceiveRecordExport;
import com.dingyx.ps.model.po.*;
import com.dingyx.ps.model.vo.*;
import com.dingyx.ps.repository.UserCacheRepository;
import com.dingyx.ps.util.Constant;
import com.dingyx.ps.util.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Api(description="管理端接口")
@RestController
@RequestMapping(value = "/admin")
public class AdminController {
    @Resource
    private ManagerUserMapper managerUserMapper;
    @Resource
    private MemberListMapper memberListMapper;
    @Resource
    private GoodsListMapper goodsListMapper;
    @Resource
    private ReceiveRecordMapper receiveRecordMapper;
    @Autowired
    private UserCacheRepository userCacheRepository;

    @ApiOperation(value = "【管理端】 管理员登陆", response = ManagerUserVO.class)
    @PostMapping("/loginIn")
    public ReturnT loginIn(@RequestBody @Validated ManagerLoginInPO param) {
        log.info("receiveRecord-->{}", JSONObject.toJSONString(param));
        QueryWrapper<ManagerUserDTO> query = new QueryWrapper<>();
        query.eq("manager_login_name", param.getManagerLoginName());
        query.eq("manager_login_pw", param.getManagerLoginPw());
        ManagerUserDTO result = managerUserMapper.selectOne(query);
        if(Objects.isNull(result)){
            return ReturnT.ERROR("用户名或密码错误");
        }
        ManagerUserVO enterpriseUser = new ManagerUserVO();
        BeanUtils.copyProperties(result, enterpriseUser);

        // 设置登录token
        String token = Constant.SESSION_KEY_ENTERPRISE + IdUtil.simpleUUID();
        enterpriseUser.setToken(token);
        // 缓存管理用户信息
        userCacheRepository.cacheUserInfo(token, enterpriseUser, Constant.SESSION_KEY_USER_EXPIRE);
        return ReturnT.SUCCESS(enterpriseUser);
    }

    @ApiOperation(value = "【管理端】 领取记录", response = ReceiveRecordVO.class)
    @PostMapping("/receiveRecord")
    public ReturnT receiveRecord(@RequestBody @Validated ReceiveRecordPO param) {
        log.info("receiveRecord-->{}", JSONObject.toJSONString(param));
        Page<ReceiveRecordDTO> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<ReceiveRecordDTO> pages = receiveRecordMapper.selectPageList(page);
        return ReturnT.SUCCESS(pages);
    }

    @ApiOperation(value = "【管理端】 会员管理", response = MemberListVO.class)
    @PostMapping("/memberList")
    public ReturnT memberList(@RequestBody @Validated MemberListPO param) {
        log.info("receiveRecord-->{}", JSONObject.toJSONString(param));
//        Page<ReceiveRecordDTO> page = new Page<>(param.getPageNum(), param.getPageSize());
        return ReturnT.SUCCESS();
    }

    @ApiOperation(value = "【管理端】 领取规则", response = GoodsListVO.class)
    @PostMapping("/claimRule")
    public ReturnT goodsList(@RequestBody @Validated PageEntity param) {
        log.info("receiveRecord-->{}", JSONObject.toJSONString(param));
        Page<GoodsListDTO> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<GoodsListDTO> pages = goodsListMapper.selectPageList(page);
        return ReturnT.SUCCESS(pages);
    }

    @ApiOperation(value = "【管理端】 更新规则", response = GoodsListVO.class)
    @PostMapping("/updateClaimRule")
    public ReturnT updateClaimRule(@RequestBody @Validated GoodsListPO param) {
        log.info("receiveRecord-->{}", JSONObject.toJSONString(param));
        GoodsListDTO dto = new GoodsListDTO();
        BeanUtils.copyProperties(param, dto);
        int result = goodsListMapper.updateById(dto);
        return ReturnT.SUCCESS(result);
    }

    @ApiOperation(value = "【管理段】导出商品领取记录", produces = "application/octet-stream")
    @GetMapping("/ReceiveRecordExport")
    public void ReceiveRecordExport() {
        // 领取记录
        Page<ReceiveRecordDTO> page = new Page<>(1, Long.MAX_VALUE);
        IPage<ReceiveRecordDTO> pages = receiveRecordMapper.selectPageList(page);
        List<ReceiveRecordDTO> records = pages.getRecords();
        if(CollectionUtil.isEmpty(records)){
            return;
        }
        List<ReceiveRecordExport> recordExports = new ArrayList<>();
        for(ReceiveRecordDTO record : records){
            ReceiveRecordExport recordExport = new ReceiveRecordExport();
            BeanUtils.copyProperties(record, recordExport);
            if (record.getReceiveEnable() != null && record.getReceiveEnable() == 0) {
                recordExport.setReceiveEnableStr("领取成功");
            } else {
                recordExport.setReceiveEnableStr("领取失败");
            }
            recordExports.add(recordExport);
        }
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ReceiveRecordExport.class, recordExports);
        String fileName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        try {
            ExcelUtils.downLoadExcel(fileName,workbook);
        }catch (Exception e){
            log.error(ExceptionUtil.getMessage(e));
        }
    }

    @ApiOperation(value = "【管理段】导出会员列表", produces = "application/octet-stream")
    @GetMapping("/memberExport")
    public void memberExport() {
        // 领取记录
        Page<MemberListDTO> page = new Page<>(1, Long.MAX_VALUE);
        QueryWrapper<MemberListDTO> queryWrapper = new QueryWrapper<>();
        IPage<MemberListDTO> pages = memberListMapper.selectPage(page, queryWrapper);
        List<MemberListDTO> records = pages.getRecords();
        if(CollectionUtil.isEmpty(records)){
            return;
        }
        List<MemberExport> recordExports = new ArrayList<>();
        for(MemberListDTO record : records){
            MemberExport recordExport = new MemberExport();
            BeanUtils.copyProperties(record, recordExport);
            recordExports.add(recordExport);
        }
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), MemberExport.class, recordExports);
        String fileName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        try {
            ExcelUtils.downLoadExcel(fileName,workbook);
        }catch (Exception e){
            log.error(ExceptionUtil.getMessage(e));
        }
    }
}